/*
 * Copyright (C) 2010 EPRO
 */
package com.epro.dx.fragment;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.activity.BaseFragmentActivity;
import com.epro.dx.adapter.ProductListAdapter;
import com.epro.dx.enable.NetworkBroadcastReceiver;
import com.epro.dx.enable.NetworkBroadcastReceiver.NetWorkCallBack;
import com.epro.dx.listenner.MyAsyncTaskListenner;
import com.epro.dx.listenner.OnSortViewItemClickListenner;
import com.epro.dx.listenner.OnViewGroupScrollListenner;
import com.epro.dx.pullview.PullToRefreshBase;
import com.epro.dx.pullview.PullToRefreshBase.Mode;
import com.epro.dx.pullview.PullToRefreshBase.OnRefreshListener2;
import com.epro.dx.pullview.PullToRefreshGridView;
import com.epro.dx.task.GetHomeBannerAsyncTask;
import com.epro.dx.task.GetProductsFromSkusAsyncTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.OnekeyFilterLocalUtil;
import com.epro.dx.widget.SortView;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.HitBuilders.EventBuilder;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.CouponActiveModel;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.facade.model.SearchModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.JsonFormat;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品列表展示Activity 实现商品列表展示，并可按指定的方式进行排序
 *
 * @author cw55072
 * @version [1.0, 2010-09-02]
 */

public class ProductListFragment extends Fragment implements
        NetWorkCallBack, OnClickListener, OnViewGroupScrollListenner,
        OnSortViewItemClickListenner {
    private static final String TAG = "ProductListActivity";
    //	ParcelableModel<ArrayList<ProductModel>> productlist = null;
    ArrayList<ProductModel> productlist = null;

    private PullToRefreshGridView gridViewLayout;

    /**
     * 商品列表适配器
     */
    private ProductListAdapter adapterProduct;

    /**
     * 默认catalogId不可能值
     */
    private static final int DEFAULT_CATALOGID = -2;

    /**
     * 目录Id
     */
    private int catalogId = DEFAULT_CATALOGID;

    /**
     * 商品列表集合
     */
    private ArrayList<ProductModel> products = null;

    /**
     * 接口返回商品列表
     */
    private List<ProductModel> productList = null;

    /**
     * 开始数据索引位置
     */
    private int pageIndex = 1;

    /**
     * 目录名
     */
    private String catalogName;

    private SortView sortLayout;

    private Animation toUp, toDown;

    private boolean isUpStarted, isDownStarted;

    private int firstVisiblePosition;

    private String productType, fromWhere;

    private boolean isReLoad;
    //是否正在加载数据
    private boolean isLoadingList = false;

    // 返回top按钮
    private ImageButton toTop;
    private Tracker tracker;
    private EventBuilder eventBuilder;

    private int densityDpi;

    /**
     * CouponCode
     */
    private String couponCode;
    private Intent intent;
    private RelativeLayout filterModelLayout;
    private ArrayList<Integer> bfdSkus;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.activity_productlist, null);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tracker = ((DXApplication) getActivity().getApplication())
                .getTracker(TrackerName.APP_TRACKER);
        eventBuilder = new EventBuilder();

        // 不显示标题
        initView();
        initAnimation();
        initDate(savedInstanceState);


    }

    public static ProductListFragment getInstance(int browseID) {
        ProductListFragment fragment = new ProductListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("browseID", browseID);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        String screenName;
        if (Constant.FROM_HOME.equals(fromWhere)) {
            screenName = productType;
        } else {
            screenName = fromWhere;
        }
        tracker.setScreenName("ProductList From " + screenName);
        tracker.send(new HitBuilders.ScreenViewBuilder().build());
    }


    @Override
    public void onPause() {
        super.onPause();
        tracker.setScreenName(null);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString(Constant.PRODUCTLIST_TYPE, productType);
        outState.putString(Constant.TO_PRODUCTLIST_FROM, catalogName);
        outState.putString(Constant.PRODUCT_TITLE, fromWhere);
        outState.putString("CouponCode", couponCode);
        outState.putInt("catalogId", catalogId);
        outState.putParcelableArrayList("productlist", productlist);
        outState.putIntegerArrayList(HomeFragment.HOMEBFDSKULIST, bfdSkus);
        super.onSaveInstanceState(outState);
    }

    public void initDate(Bundle outState) {
        intent = getActivity().getIntent();
        if (null != intent) {
            productType = intent.getStringExtra(Constant.PRODUCTLIST_TYPE);
            fromWhere = intent.getStringExtra(Constant.TO_PRODUCTLIST_FROM);
            catalogId = intent.getIntExtra("catalogId", 0);
//			productlist = intent.getParcelableExtra("productlist");
            productlist = intent.getParcelableArrayListExtra("productlist");
            catalogName = intent.getStringExtra(Constant.PRODUCT_TITLE);
            couponCode = intent.getStringExtra("CouponCode");
            bfdSkus = intent.getIntegerArrayListExtra(HomeFragment.HOMEBFDSKULIST);
        } else if (null != outState) {
            productType = outState.getString(Constant.PRODUCTLIST_TYPE);
            fromWhere = outState.getString(Constant.TO_PRODUCTLIST_FROM);
            catalogId = outState.getInt("catalogId", 0);
            productlist = outState.getParcelableArrayList("productlist");
            catalogName = outState.getString(Constant.PRODUCT_TITLE);
            couponCode = outState.getString("CouponCode");
            bfdSkus = outState.getIntegerArrayList(HomeFragment.HOMEBFDSKULIST);
        }

        if (getArguments() != null) {
            catalogId = getArguments().getInt("browseID", -2);
        }

        if (Constant.FROM_COUPON.equals(fromWhere) || Constant.FROM_HOME_BFD.equals(fromWhere)) {
            pageIndex = 0;
        }
        // 目录浏览里直接传过来的商品列表
        densityDpi = ((BaseFragmentActivity) getActivity()).getDensityDpi();

//		if (null != catalogName) {
//			setTitleContent(catalogName);
//		} else {
//			setTitleContent(getString(R.string.product_list));
//		}
//		if (null != productlist && productlist instanceof ParcelableModel) {
//			products = ((ParcelableModel<ArrayList<ProductModel>>) productlist)
//					.getData();
//		}
        if (null != productlist) {
            products = productlist;
        }
        if (null == products || products.isEmpty()) {
            products = new ArrayList<ProductModel>();
            adapterProduct = new ProductListAdapter(getActivity(),
                    products, false, gridViewLayout, this, densityDpi, tracker);
            gridViewLayout.setAdapter(adapterProduct);
            NetworkBroadcastReceiver.setCallBack(this);
            // showWaitingDialog();
            // new ProductListAsyncTask(pageIndex).execute();
            // loadingLayout.setVisibility(View.VISIBLE);
            showLoadingLayout(gridViewLayout);
            sortLayout.setSortBtnEnable(false);
            executeTask();

        } else {
            adapterProduct = new ProductListAdapter(getActivity(),
                    products, false, gridViewLayout, this, densityDpi, tracker);
            adapterProduct.setCurrencyCode(intent.getStringExtra("CurrencyCode"), intent.getStringExtra("CurrencyCodeStr"));
            gridViewLayout.setAdapter(adapterProduct);
        }
    }

    /**
     * 动画初始类
     */
    private void initAnimation() {
        toUp = AnimationUtils.loadAnimation(getActivity(), R.anim.sort_up);
        toDown = AnimationUtils.loadAnimation(getActivity(), R.anim.sort_down);
        toUp.setAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                isUpStarted = true;
                sortLayout.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                sortLayout.setVisibility(View.GONE);
                isUpStarted = false;
            }
        });
        toDown.setAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                sortLayout.setVisibility(View.VISIBLE);
                isDownStarted = true;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                isDownStarted = false;
            }
        });

        copyfromActivity();
    }

    /**
     * 初始化相关
     */
    private void initView() {
        sortLayout = (SortView) getView().findViewById(R.id.sort_layout);
        sortLayout.setPopularityStr("d=Popularity");
        sortLayout.setDefaultSortStyle();
        sortLayout.setOnSortViewItemClickListenner(this);
        gridViewLayout = (PullToRefreshGridView) getView().findViewById(R.id.data_list);
        toTop = (ImageButton) getView().findViewById(R.id.productlist_totop);
        toTop.setOnClickListener(this);


        filterModelLayout = (RelativeLayout) getView().findViewById(R.id.on_filter_model_layout);
        String config;
        if (ActivityUtil.isLogin(getActivity())) {
            config = StringUtil.getConfig(ActivityUtil.getCustomerID() + ServerConstant.OneKeyFilter.ISFILTERKEY_ONLINE, "false");
        } else {
            config = StringUtil.getConfig(ServerConstant.OneKeyFilter.ISFILTERKEY_LOCAL, "false");
        }
        filterModelLayout.setVisibility("true".equals(config) ? View.VISIBLE : View.GONE);
        getView().findViewById(R.id.on_filter_model_layout_delete).setOnClickListener(this);

        gridViewLayout.setOnRefreshListener(new OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(
                    PullToRefreshBase<GridView> refreshView) {
                loadDatas(false);
            }

            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<GridView> refreshView) {
                if (!isLoadingList)
                    loadDatas(true);
            }
        });

    }

    @Override
    public void netWorkChangeCallBack(boolean isLoadMore) {
        // 网络由不可用变为可用
        if (isLoadMore) {
            pageIndex += 1;
            if (null != adapterProduct) {
                adapterProduct.notifyDataSetChanged();
                gridViewLayout.onRefreshComplete();
            } else {
                // new ProductListAsyncTask(pageIndex).execute();
                executeTask();
            }
        }
    }

    /**
     * 加载数据 <br>
     * isLoadMore 是否显示更多
     */
    private void loadDatas(boolean isLoadMore) {
        isLoadingList = true;
        if (isLoadMore) {
            pageIndex += 1;
        } else {
            if (Constant.FROM_COUPON.equals(fromWhere) || Constant.FROM_HOME_BFD.equals(fromWhere)) {
                pageIndex = 0;
            } else {
                pageIndex = 1;
            }

            products.clear();
            if (null != adapterProduct) {
                adapterProduct.setFirstEnter(true);
            }
        }
        // new ProductListAsyncTask(pageIndex).execute();
        executeTask();
        if (Logger.isLog) {
            Logger.e("start:",
                    pageIndex + "loadProduct.size():" + products.size()
                            + "initNum:");
        }
    }


    /**
     * 获取Coupon的活动产品
     *
     * @author Administrator
     */
    protected class GetCategoryProducts extends AsyncTask<Void, Void, String> {
        private CouponActiveModel couponActiveModel;
        private int start;
        private int categoryId;
        private String couponCode;
        private String currentItemStr;

        public GetCategoryProducts(int start, int categoryId, String couponCode) {
            this.start = start;
            this.categoryId = categoryId;
            this.couponCode = couponCode;
        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            currentItemStr = sortLayout.getCurrentSortType();
        }

        @Override
        protected String doInBackground(Void... params) {
            boolean isFilter;
            if (ActivityUtil.isLogin(getActivity())) {
                isFilter = "true".equals(StringUtil.getConfig(ActivityUtil.getCustomerID() + ServerConstant.OneKeyFilter.ISFILTERKEY_ONLINE, "false"));
            } else {
                isFilter = "true".equals(StringUtil.getConfig(ServerConstant.OneKeyFilter.ISFILTERKEY_LOCAL, "false"));
            }
            try {
                couponActiveModel = ProviderFactory
                        .createCouponServiceProvider().FindDiscountProducts(
                                couponCode, Constant.LIST_PAGE_COUNT, start,
                                categoryId, currentItemStr,
                                ActivityUtil.getCustomerID(), isFilter, OnekeyFilterLocalUtil.getLocalCategoryIds(getActivity()));
            } catch (DxException e) {
                return e.getErrCode();
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if (isVisible()) {
                // hideWaitingDialog();
                hideAllLayout(gridViewLayout);
                sortLayout.setSortBtnEnable(true);
                if ("0".equals(result) && null != couponActiveModel) {
                    productList = couponActiveModel.getProducts();
                    if (productList != null && productList.size() > 0) {
                        adapterProduct.setCurrencyCode(couponActiveModel.getCurrencyCode(), couponActiveModel.getCurrencyCodeStr());
                    }
                }
                refreshUI(result, start);
            }
            isLoadingList = false;
        }
    }

    /**
     * 商品列表数据加载异步类
     *
     * @author hjd008
     * @version [版本号, 2012-12-17]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     */

    protected class ProductListAsyncTask extends AsyncTask<Void, Void, String> {
        private int start;
        private SearchModel searchModel;
        private String currentItemStr;

        public ProductListAsyncTask(int start) {
            this.start = start;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            currentItemStr = sortLayout.getCurrentSortType();
        }

        @Override
        protected String doInBackground(Void... params) {
            String currencyCode = StringUtil.getConfig(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE, getString(R.string.currency_default_currencyCode));
            try {
                searchModel = ProviderFactory.createProductProvider()
                        .getProductListByCategoryId(start,
                                Constant.LIST_PAGE_COUNT,
                                currentItemStr, 0.00,
                                Double.MAX_VALUE, 0.00, catalogId, currencyCode);

            } catch (DxException e) {
                return e.getErrCode();
            } catch (Exception e) {
                Logger.e("BrowsListActivity", "ProductListAsyncTask", e);
                return e.getMessage();
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if (isVisible()) {
                hideAllLayout(gridViewLayout);
                sortLayout.setSortBtnEnable(true);
                if ("0".equals(result)) {
                    productList = searchModel.getProductModels();
                    adapterProduct.setCurrencyCode(searchModel.getCurrencyCode(), searchModel.getCurrencyCodeSymbol());
                }
                refreshUI(result, start);
            }
            isLoadingList = false;
        }
    }

    private void setNoDataView(int start) {
        int tStart = 1;
        if (Constant.FROM_COUPON.equals(fromWhere) || Constant.FROM_HOME_BFD.equals(fromWhere)) {
            tStart = 0;
        }
        if (start == tStart) {
            sortLayout.setVisibility(View.GONE);
            showEmptyLayout(gridViewLayout, R.string.no_products_suggest,
                    R.drawable.sorry);
            return;
        }
    }

    private void refreshUI(String result, int start) {
        if ("0".equals(result)) {
            hideAllLayout(gridViewLayout);
            sortLayout.setVisibility(View.VISIBLE);
            if (null != productList && !productList.isEmpty()) {
                if (productList.size() == 0) {
                    setNoDataView(start);
                    return;
                }
                products.addAll(productList);
                if (isReLoad) {
                    adapterProduct.notifyDataSetInvalidated();
                    isReLoad = false;
                } else {
//					adapterProduct.isFirstEnter = true;
                    adapterProduct.notifyDataSetChanged();
                }

                gridViewLayout.onRefreshComplete();
                // gridViewLayout.gridViewSmoothScrollTo(0);
                // 当数据没满一夜数据时说明数据已经加载完毕 上拉加载
                if (productList.size() < Constant.LIST_PAGE_COUNT) {
                    gridViewLayout.setMode(Mode.PULL_FROM_START);
                } else {
                    gridViewLayout.setMode(Mode.BOTH);
                }
            }
            // 如果没有数据就展示当前的数据
            else {
                setNoDataView(start);
                adapterProduct.notifyDataSetChanged();
                gridViewLayout.onRefreshComplete();
                gridViewLayout.setMode(Mode.PULL_FROM_START);
            }
        } else {
            // 加载第一页因网络未连接或者超时显示网络异常页面
            if (isFirstPage()) {
                sortLayout.setVisibility(View.GONE);
                if (ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE.equals(result)) {
                    showErrorLayout(gridViewLayout, R.string.internet_error,
                            R.string.internet_suggest, R.drawable.no_internet);
                } else {
                    showErrorLayout(gridViewLayout, R.string.server_busy,
                            R.string.server_suggest, R.drawable.no_internet);
                }
                retryBtn.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showLoadingLayout(null);
                        sortLayout.setSortBtnEnable(false);
                        adapterProduct.setFirstEnter(true);
                        executeTask();
                    }
                });
            } else {
                AlertToast.alert(getActivity(),
                        ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                // 异常问题时问题
                adapterProduct.notifyDataSetChanged();
                gridViewLayout.onRefreshComplete();
                gridViewLayout.setMode(Mode.BOTH);
                pageIndex--;
            }
        }
    }

    /**
     * 不同FromWhere调用不同的接口
     */
    public void executeTask() {
        if (Constant.FROM_CATEGORY.equals(fromWhere)) {
            AsyncTaskUtil.executeTask(new ProductListAsyncTask(pageIndex));
        } else if (Constant.FROM_HOME.equals(fromWhere)) {
            AsyncTaskUtil.executeTask(new GetHomeBannerAsyncTask(getActivity(), pageIndex,
                    Constant.LIST_PAGE_COUNT, true, catalogId, productType,
                    sortLayout.getCurrentSortType(), new MyAsyncTaskListenner() {

                @Override
                public void onPreTask() {

                }

                @Override
                public void onPostTask(String result, Object obj) {
                    SearchModel searchModel = (SearchModel) obj;

                    if (isVisible()) {
                        sortLayout.setSortBtnEnable(true);
                        hideAllLayout();
                        if ("0".equals(result)) {
                            productList = searchModel.getProductModels();
                            adapterProduct.setCurrencyCode(searchModel.getCurrencyCode(), searchModel.getCurrencyCodeSymbol());
                        }
                        refreshUI(result, pageIndex);
                    }
                    isLoadingList = false;
                }
            }));
        } else if (Constant.FROM_COUPON.equals(fromWhere)) {
            AsyncTaskUtil.executeTask(new GetCategoryProducts(pageIndex, catalogId, couponCode));
        } else if (Constant.FROM_HOME_BFD.equals(fromWhere)) {
            AsyncTaskUtil.executeTask(new GetProductsFromSkusAsyncTask(bfdSkus, getActivity(),
                    pageIndex, Constant.LIST_PAGE_COUNT, sortLayout.getCurrentSortType(),
                    catalogId, true, new MyAsyncTaskListenner() {

                @Override
                public void onPreTask() {
                }

                @Override
                public void onPostTask(String result, Object obj) {
                    @SuppressWarnings("unchecked")
                    ArrayList<ProductModel> modelList = (ArrayList<ProductModel>) obj;
                    if (isVisible()) {
                        sortLayout.setSortBtnEnable(true);
                        hideAllLayout();
                        if ("0".equals(result)) {
                            productList = modelList;
                            if (null != modelList && modelList.size() > 0) {
                                adapterProduct.setCurrencyCode(modelList.get(0).getCurrencyCode(), modelList.get(0).getCurrencyCodeSymbol());
                            }
                        }
                        refreshUI(result, pageIndex);
                    }
                    isLoadingList = false;
                }
            }));
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.productlist_totop:// 点击返回顶部按钮，返回到商品列表的顶部
                adapterProduct.notifyDataSetInvalidated();
                return;
            case R.id.on_filter_model_layout_delete:// 隐藏过滤模式提示信息
                filterModelLayout.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    /**
     * 排序请求
     */
    private void sortRequest() {
        if (Constant.FROM_COUPON.equals(fromWhere) || Constant.FROM_HOME_BFD.equals(fromWhere)) {
            pageIndex = 0;
        } else {
            pageIndex = 1;
        }
        products.clear();
        if (null != adapterProduct) {
            adapterProduct.setFirstEnter(true);
        }
        // showWaitingDialog();
        sortLayout.setSortBtnEnable(false);
        showLoadingLayout(gridViewLayout);
        isReLoad = true;
        executeTask();
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        // 判断列表当前可见的第一条数据位置，设置返会顶部按钮是否可见
        if (view.getFirstVisiblePosition() > 4) {
            toTop.setVisibility(View.VISIBLE);
        } else {
            toTop.setVisibility(View.GONE);
        }

    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
            firstVisiblePosition = view.getFirstVisiblePosition() + 2;
        }
        // 实现预加载功能
        int autoLoadCount = products.size() - view.getFirstVisiblePosition();
        if (autoLoadCount < 8 && !isLoadingList && gridViewLayout.getMode() == Mode.BOTH) {
            // 滑到一半进行预加载
            loadDatas(true);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        NetworkBroadcastReceiver.setCallBack(null);
        if (null != adapterProduct) {
            adapterProduct.recleBitmap();
        }
    }

    @Override
    public void onPopulayityClick() {
        eventBuilder.setCategory("Sort").setAction("sort_popularity");
        tracker.send(eventBuilder.build());
        sortRequest();
    }

    @Override
    public void onPriceClick() {
        eventBuilder.setCategory("Sort").setAction("sort_price");
        tracker.send(eventBuilder.build());
        sortRequest();
    }

    @Override
    public void onDisCountClick() {
        eventBuilder.setCategory("Sort").setAction("sort_disCount");
        tracker.send(eventBuilder.build());
        sortRequest();
    }

    /**
     * @return
     * @创建：Tony 2016-5-27下午5:56:56
     * @描述：判断当前是否为第一页
     */
    private boolean isFirstPage() {
        if (Constant.FROM_COUPON.equals(fromWhere) || Constant.FROM_HOME_BFD.equals(fromWhere)) {
            return pageIndex == 0;
        } else {
            return pageIndex == 1;
        }
    }


    /***
     * ---------------------------------------------------------------------
     ***/

    //数据为空页面
    protected LinearLayout emptyLayout;
    //请求加载页面
    private LinearLayout loadingLayout;
    //数据为空页面描述
    private TextView emptyContent;
    //错误类型标题
    private TextView errorTitle;
    //错误描述
    private TextView errorContent;
    //重试按钮
    public Button retryBtn;

    private ImageView errorIcon;

    private void copyfromActivity() {
        emptyLayout = (LinearLayout) getView().findViewById(R.id.layout_empty);
        if (null != emptyLayout) {
            errorTitle = (TextView) getView().findViewById(R.id.error_type);
            errorIcon = (ImageView) getView().findViewById(R.id.pic_empty);
            errorContent = (TextView) getView().findViewById(R.id.tv_empty);
            retryBtn = (Button) getView().findViewById(R.id.try_again);
        }
        loadingLayout = (LinearLayout) getView().findViewById(R.id.loading_layout);
    }

    /**
     * 展示加载页面
     *
     * @param view
     */
    protected void showLoadingLayout(View view) {
        if (null != view) {
            view.setVisibility(View.GONE);
        }
        if (null != emptyLayout) {
            emptyLayout.setVisibility(View.GONE);
        }
        if (null != loadingLayout) {
            loadingLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 展示错误页面(错误界面更空界面共用同一界面)
     *
     * @param view
     */
    protected void showErrorLayout(View view, int titleId, int contentId, int resId) {
        if (null != view) {
            view.setVisibility(View.GONE);
        }
        if (null != emptyLayout) {
            emptyLayout.setVisibility(View.VISIBLE);
            if (titleId != 0) {
                errorTitle.setVisibility(View.VISIBLE);
                errorTitle.setText(titleId);
            } else {
                errorTitle.setVisibility(View.INVISIBLE);
            }
            if (contentId != 0) {
                errorContent.setVisibility(View.VISIBLE);
                errorContent.setText(contentId);
            } else {
                errorContent.setVisibility(View.INVISIBLE);
            }
            errorIcon.setImageResource(resId);
            retryBtn.setVisibility(View.VISIBLE);
        }
        if (null != loadingLayout) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    /**
     * @param result
     * @param v
     * @创建：Tony 2016-4-14下午2:04:39
     * @描述：根据返回码显示错误页面
     */
    protected void showErrorLayout(String result, View v) {
        if (ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE.equals(result)) {
            showErrorLayout(v, R.string.internet_error, R.string.internet_suggest, R.drawable.no_internet);

        } else {
            showErrorLayout(v, R.string.server_busy, R.string.server_suggest, R.drawable.no_internet);

        }
    }

    /**
     * 展示空数据页面(错误界面更空界面共用同一界面)
     *
     * @param view
     * @param contentId
     * @param resId
     */
    protected void showEmptyLayout(View view, int contentId, int resId) {
        if (null != view) {
            view.setVisibility(View.GONE);
        }
        if (null != emptyLayout) {
            emptyLayout.setVisibility(View.VISIBLE);
            errorContent.setText(contentId);
            errorIcon.setImageResource(resId);
            retryBtn.setVisibility(View.GONE);
            errorTitle.setVisibility(View.INVISIBLE);
        }
        if (null != loadingLayout) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 隐藏所有辅助界面
     */
    protected void hideAllLayout() {
        if (null != emptyLayout) {
            emptyLayout.setVisibility(View.GONE);
        }
        if (null != loadingLayout) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 隐藏所有辅助界面 显示数据界面
     *
     * @param view
     */
    protected void hideAllLayout(View view) {
        if (null != view) {
            view.setVisibility(View.VISIBLE);
        }
        if (null != emptyLayout) {
            emptyLayout.setVisibility(View.GONE);
        }
        if (null != loadingLayout) {
            loadingLayout.setVisibility(View.GONE);
        }
    }
}